package com.tiantian.homework_2_video_player.controller;

import com.tiantian.homework_2_video_player.mapper.VideoMapper;
import com.tiantian.homework_2_video_player.pojo.Result;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.Resource;
import org.springframework.core.io.UrlResource;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.nio.file.Path;
import java.nio.file.Paths;

@RestController
@RequestMapping("/videos")
public class VideoController {

    @Autowired
    private VideoMapper videoMapper;

    /**
     * 处理下载视频请求
     *
     * @param id 视频id
     * @return ResponseEntity<Resource> Spring Http 响应实体对象，包含视频文件的基本信息和二进制数据流
     */
    @GetMapping("/{id}")
    public ResponseEntity<Resource> downloadFileFromLocal(@PathVariable Integer id) {
        try {
            // 根据视频id获取视频文件的资源
            Path path = Paths.get(
                    videoMapper.getVideoById(id)
                            .getPath());
            Resource resource = new UrlResource(path.toUri());
            long fileSizeMB = resource.contentLength() / 1024 / 1024; // 文件大小（单位：字节）
            System.out.println("视频文件大小为" + fileSizeMB + "mb");
            // 如果资源存在，则将响应码设置为 200 OK 并返回视频文件流
            if (resource.exists()) {
                return ResponseEntity.ok()
                        .contentType(MediaType.APPLICATION_OCTET_STREAM)
                        .body(resource);
            } else {
                // 如果资源不存在，则响应码设为 404 NOT FOUND
                return ResponseEntity.notFound().build();
            }
        } catch (Exception e) {
            // 如果出现异常，则响应码设为服务器内部错误 500
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).build();
        }
    }

    /**
     * 获取视频播放列表
     * @return 视频列表
     */
    @GetMapping("/all")
    public Result getVideList() {
        return Result.ok(videoMapper.getAllVideos());
    }
}
